package com.yuhong.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuhong.springbootinit.model.entity.Application;
import com.yuhong.springbootinit.model.entity.Profile;
import com.yuhong.springbootinit.model.entity.UserProfile;
import com.yuhong.springbootinit.constant.CommonConstant;
import com.yuhong.springbootinit.model.dto.profile.ProfileQueryRequest;
import com.yuhong.springbootinit.model.entity.User;
import com.yuhong.springbootinit.model.vo.ProfileVO;
import com.yuhong.springbootinit.service.ApplicantService;
import com.yuhong.springbootinit.service.ApplicationService;
import com.yuhong.springbootinit.service.ProfileService;
import com.yuhong.springbootinit.mapper.ProfileMapper;
import com.yuhong.springbootinit.service.UserProfileService;
import com.yuhong.springbootinit.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author 10467
* @description 针对表【profile】的数据库操作Service实现
* @createDate 2025-02-22 13:52:10
*/
@Service
public class ProfileServiceImpl extends ServiceImpl<ProfileMapper, Profile>
    implements ProfileService{

    private static final String UPLOAD_DIR = "E:\\resumes";

    @Resource
    private UserProfileService userProfileService;

    @Resource
    private ApplicationService applicationService;

    // TODO: 2025/5/4 添加解析
    @Override
    public String uploadProfile(MultipartFile file, User user) {

        if (file.isEmpty()) {
            return null;
        }

        QueryWrapper<UserProfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserProfile::getUserId, user.getUserAccount());
        UserProfile oldUserProfile = userProfileService.getOne(queryWrapper);


        if(oldUserProfile != null){
            String profileId = oldUserProfile.getProfileId();
            QueryWrapper<Profile> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(Profile::getProfileId, profileId);
            Profile oldProfile = this.getOne(queryWrapper1);
            //事务
            userProfileService.removeById(oldUserProfile);
            this.removeById(oldProfile);
        }

        try {
            // 以用户上传文件的名字作为新文件名
            String newFileName = file.getOriginalFilename();

            // 定义文件保存路径
            Path filePath = Paths.get(UPLOAD_DIR, newFileName);

            // 使用输入输出流将文件保存到本地文件系统
            InputStream inputStream = file.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(new File(filePath.toString()));
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer))!= -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();

            // 将文件路径记录在 Profile 类的 path 中
            String profileId = UUID.randomUUID().toString();
            Profile profile = new Profile();
            profile.setPath(filePath.toString());
            profile.setProfileId(profileId);
            save(profile);

            // 记录文件与用户对应关系在 UserProfile 类中

            UserProfile userProfile = new UserProfile();
            userProfile.setUserId(user.getUserAccount());
            userProfile.setProfileId(profileId);
//            userProfile.setUserName(userProfile.getUserName());
//            userProfile.setCreateTime(new Date());
//            userProfile.setUpdateTime(new Date());
            userProfileService.save(userProfile);

            return profile.getPath();

        } catch (IOException e) {
            return null;
        }

    }

    @Override
    public ProfileVO getProfileVO(Profile profile) {
        return BeanUtil.copyProperties(profile, ProfileVO.class);
    }

    @Override
    public QueryWrapper<Profile> getQueryWrapper(ProfileQueryRequest profileQueryRequest) {

        Long id = profileQueryRequest.getId();
        String bg = profileQueryRequest.getBg();
        String userName = profileQueryRequest.getUserId();
        int current = profileQueryRequest.getCurrent();
        int pageSize = profileQueryRequest.getPageSize();
        String sortField = profileQueryRequest.getSortField();
        String sortOrder = profileQueryRequest.getSortOrder();

        QueryWrapper<Profile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ObjectUtils.isNotEmpty(bg), Profile::getBg, bg);
        queryWrapper.lambda().eq(ObjectUtils.isNotEmpty(id), Profile::getId, id);
        queryWrapper.lambda().eq(ObjectUtils.isNotEmpty(userName), Profile::getUserName, userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);

        return queryWrapper;
    }

    @Override
    public Page<ProfileVO> getProfileVOPage(Page<Profile> profilePage, HttpServletRequest request) {
        List<Profile> postList = profilePage.getRecords();
        Page<ProfileVO> profileVOPage = new Page<>(profilePage.getCurrent(), profilePage.getSize(), profilePage.getTotal());
        if (CollUtil.isEmpty(postList)) {
            return profileVOPage;
        }

        List<ProfileVO> profileVOS = BeanUtil.copyToList(postList, ProfileVO.class);
        profileVOPage.setRecords(profileVOS);

        return profileVOPage;
    }

    @Override
    public Profile getProfileByProfileId(String profileId) {

        QueryWrapper<Profile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Profile::getProfileId, profileId);

        return this.getOne(queryWrapper);
    }

    @Override
    public List<String> batchSelection(String positionId) {

//        QueryWrapper<Application> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(Application::getPositionId, positionId);

        applicationService.lambdaUpdate()
                .eq(Application::getPositionId, positionId)
                .set(Application::getStatus, 2)
                .update();

        // 查询该 positionId 对应的 profileId 列表（去重可加 distinct）

        return applicationService.lambdaQuery()
                .eq(Application::getPositionId, positionId)
                .select(Application::getProfileId)
                .list()
                .stream()
                .map(Application::getProfileId)
                .filter(Objects::nonNull)
                // .distinct() // 如果只需要唯一 profileId，请取消注释
                .collect(Collectors.toList());


    }
}




